package com.lin.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtils {
	/**
	 * 发邮件的方法
	 * @param to :收件人
	 * @param code :激活码
	 */
	public static void sendMail(String to,String code){
		/**
		 * 1.创建一个session(用于连接对象)
		 */
		Properties props = new Properties();
		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("service@estore.com", "123");
			}
			
		});
		/**
		 * 2.创建一个Message对象:邮件对象
		 */
		Message message = new MimeMessage(session);
		
		
		try {
			// 设置发件人
			message.setFrom(new InternetAddress("service@estore.com"));
			// 设置收件人
			message.setRecipient(RecipientType.TO, new InternetAddress(to));
			// 设置主题:
		    message.setSubject("当当书城ESTORE的官方激活邮件");
		    // 设置内容
		    message.setContent("<h1>来自购物天堂ESTORE的官方激活邮件:激活请点击以下链接</h1><h3><a href='http://localhost:8080/estore/userServlet?method=active&code="+code+"'>http://localhost:8080/estore/userServlet?method=active&code="+code+"</a></h3>","text/html;charset=UTF-8");
		    // 使用Transport对象发送邮件.
		 	Transport.send(message);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
